//
//  CBWebViewController.m
//  CROSBY
//
//  Created by Harvey on 2019/2/25.
//  Copyright © 2019 Haley. All rights reserved.
//

#import "CBWebViewController.h"
#import "Const_Header.h"

#import <WebKit/WebKit.h>

@interface CBWebViewController ()<WKNavigationDelegate>

@property (strong, nonatomic) WKWebView *webView;

@property (nonatomic, strong) UIProgressView *progressView;

@property (strong, nonatomic) UIButton *reloadBtn;

@end

@implementation CBWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self p_initSubViews];
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)p_initSubViews
{
    // 1.创建WebView
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    webView.navigationDelegate = self;
    self.webView = webView;
    // 2.创建请求
    [self loadWebURL];
    // 3.将webView添加到界面
    [self.view addSubview:webView];
    
    //进度条初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 2)];
    self.progressView.progressTintColor = RGBColor(251, 0, 195, 1);
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 3.0f);
    [self.view addSubview:self.progressView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)loadWebURL
{
    // 2.创建请求
    NSString *url = @"https://www.instagram.com/kids_crosby/";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    // 3.加载网页
    [self.webView loadRequest:request];
}

- (void)refreshAction
{
    [self loadWebURL];
}

- (void)loadFailHandler
{
    self.progressView.hidden = YES;
    
    if (!_reloadBtn) {
        CGRect frame = self.webView.frame;
        _reloadBtn = [[UIButton alloc] initWithFrame:frame];
        _reloadBtn.backgroundColor = [UIColor whiteColor];
        [_reloadBtn setTitle:@"点击屏幕，重新加载" forState:UIControlStateNormal];
        [_reloadBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [_reloadBtn addTarget:self action:@selector(refreshAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_reloadBtn];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为2倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 2.0f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
            }];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - navigationDelegate
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 3.0f);
    self.progressView.progress = 0.05;
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    self.progressView.hidden = YES;
    
    [_reloadBtn removeFromSuperview];
    _reloadBtn = nil;
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [self loadFailHandler];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    [self loadFailHandler];
}

@end
